package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckSetmealMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckSetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckSetmealService.class)
@Transactional
public class CheckSetmealServiceImpl implements CheckSetmealService {
    @Autowired
    private CheckSetmealMapper checkSetmealMapper;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;//从properties文件中读取生成的html对应的目录


    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //完成分页查询，基于mabatis的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);

        Page<CheckItem> page = checkSetmealMapper.selectByCondition(queryString);
        long total = page.getTotal();
        List<CheckItem> rows = page.getResult();
        return new PageResult(total, rows);

    }

    @Override
    public List<Setmeal> findAll() {
        return checkSetmealMapper.findAll();
    }

    /**
     * 新增套餐信息，同时需要关联检查组
     *
     * @param setmeal
     * @param checkgroupIds
     */
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //新增检查组，关联检查组t_checkSetmeal表
        checkSetmealMapper.add(setmeal);

        //设置检查组与检查项的多对多关联关系，操作t_checkSetmeal_checkgroup表
        Integer setmealId = setmeal.getId();


        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                checkSetmealMapper.insert(setmealId, checkgroupId);
            }
        }
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

        generateMobileStaticHtml();
    }

    /**
     * 生成当前方法所需的静态页面
     */
    public void generateMobileStaticHtml() {
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = checkSetmealMapper.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);

    }

    /**
     * 生成套餐列表静态页面
     *
     * @param list
     */
    private void generateMobileSetmealListHtml(List<Setmeal> list) {


        Map map = new HashMap<>();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList", list);

        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);

    }


    /**
     * 生成套餐详情静态页面（N个）
     */
    private void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", checkSetmealMapper.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    /**
     * 通用方法，用于生成静态页面
     *
     * @param htmlPageName
     * @param templateName
     * @param map
     */
    private void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public Setmeal findById(int id) {

        return checkSetmealMapper.findById(id);

    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return checkSetmealMapper.findSetmealCount();
    }


}
